/*
  page.tsx
  spboucher.ai Web
  Author: Simon-Pierre Boucher
  Mail: contact@spboucher.ai
*/

import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import {
  ArrowLeft,
  Award,
  BookOpen,
  Download,
  ExternalLink,
  Github,
  Layers,
  Sparkles,
  Tag,
  Workflow,
} from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardHeader } from "@/components/ui/card";
import { IconTile } from "@/components/icon-tile";
import { Reveal } from "@/components/reveal";
import { SectionHeading } from "@/components/section-heading";
import { getAllProjectLinks, type ProjectLinks } from "@/lib/apps";
import { getDetailIcon } from "@/lib/detail-icons";
import { projectDetails } from "@/lib/project-details";

interface PageProps {
  params: Promise<{ slug: string }>;
}

function getProject(slug: string): ProjectLinks | undefined {
  return getAllProjectLinks().find((p) => p.slug === slug);
}

export function generateStaticParams() {
  return getAllProjectLinks()
    .filter((p) => projectDetails.some((d) => d.slug === p.slug))
    .map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({
  params,
}: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const project = getProject(slug);
  const detail = projectDetails.find((d) => d.slug === slug);
  if (!project || !detail) return {};
  return {
    title: `${project.name} — ${project.tagline}`,
    description: detail.hero.subheadline,
  };
}

export default async function ProjectDetailPage({ params }: PageProps) {
  const { slug } = await params;
  const project = getProject(slug);
  const detail = projectDetails.find((d) => d.slug === slug);
  if (!project || !detail) notFound();

  const statCols =
    detail.stats.length <= 3
      ? "sm:grid-cols-3"
      : detail.stats.length === 4
        ? "sm:grid-cols-2 lg:grid-cols-4"
        : detail.stats.length === 5
          ? "sm:grid-cols-3 lg:grid-cols-5"
          : "sm:grid-cols-3 lg:grid-cols-6";

  return (
    <div className="mx-auto max-w-5xl px-4 py-16 sm:px-6">
      {/* Back link */}
      <Reveal>
        <Link
          href="/apps"
          className="inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground transition-colors hover:text-primary"
        >
          <ArrowLeft className="h-4 w-4" aria-hidden="true" />
          All apps &amp; projects
        </Link>
      </Reveal>

      {/* Hero */}
      <Reveal className="mt-8">
        <div className="flex flex-col gap-6 sm:flex-row sm:items-start">
          {project.icon ? (
            <Image
              src={project.icon}
              alt={`${project.name} icon`}
              width={96}
              height={96}
              priority
              className="h-24 w-24 shrink-0 rounded-[0.9rem] border border-border shadow-[var(--shadow-soft)]"
            />
          ) : (
            <div
              aria-hidden="true"
              className="flex h-24 w-24 shrink-0 items-center justify-center rounded-[0.9rem] border border-foreground/15 bg-card text-5xl shadow-[var(--shadow-soft)]"
            >
              {project.emoji}
            </div>
          )}
          <div className="min-w-0">
            <div className="flex flex-wrap items-center gap-2">
              <Badge>
                {project.kind === "zyquo"
                  ? "Zyquo macOS Suite"
                  : project.demo
                    ? "Web Platform"
                    : "Open Source"}
              </Badge>
              {project.language && (
                <Badge variant="outline">{project.language}</Badge>
              )}
            </div>
            <h1 className="mt-3 font-display text-3xl font-bold tracking-tight sm:text-4xl">
              {project.name}
            </h1>
            <p className="mt-2 text-lg font-medium text-foreground/85">
              {detail.hero.headline}
            </p>
            <p className="mt-2 max-w-2xl text-sm leading-relaxed text-muted-foreground">
              {detail.hero.subheadline}
            </p>
            <div className="mt-5 flex flex-wrap gap-2">
              <a
                href={project.repo}
                target="_blank"
                rel="noopener noreferrer"
                className={buttonVariants({ variant: "outline", size: "sm" })}
              >
                <Github aria-hidden="true" />
                GitHub Repo
              </a>
              {project.release && (
                <a
                  href={project.release}
                  target="_blank"
                  rel="noopener noreferrer"
                  className={buttonVariants({ variant: "outline", size: "sm" })}
                >
                  <Tag aria-hidden="true" />
                  Release
                </a>
              )}
              {project.demo && (
                <a
                  href={project.demo}
                  target="_blank"
                  rel="noopener noreferrer"
                  className={buttonVariants({ variant: "default", size: "sm" })}
                >
                  <ExternalLink aria-hidden="true" />
                  Visit {project.demo.replace(/^https?:\/\//, "")}
                </a>
              )}
              {project.dmg && (
                <a
                  href={project.dmg}
                  className={buttonVariants({ variant: "default", size: "sm" })}
                >
                  <Download aria-hidden="true" />
                  Download DMG
                </a>
              )}
            </div>
          </div>
        </div>
      </Reveal>

      {/* Stats band */}
      {detail.stats.length > 0 && (
        <Reveal className="mt-14">
          <div className={`grid grid-cols-2 gap-x-8 gap-y-8 ${statCols}`}>
            {detail.stats.map((stat) => (
              <div key={stat.label} className="border-t-2 border-foreground pt-3">
                <p className="font-display text-2xl font-semibold tracking-tight text-foreground sm:text-3xl">
                  {stat.value}
                </p>
                <p className="mt-1.5 font-mono text-[0.66rem] uppercase leading-relaxed tracking-[0.12em] text-muted-foreground">
                  {stat.label}
                </p>
              </div>
            ))}
          </div>
        </Reveal>
      )}

      {/* Overview */}
      <section className="mt-14">
        <Reveal>
          <SectionHeading title="Overview" icon={BookOpen} />
        </Reveal>
        <Reveal delay={0.06}>
          <div className="mt-4 max-w-3xl space-y-4">
            {detail.overview.map((paragraph) => (
              <p
                key={paragraph.slice(0, 48)}
                className="text-sm leading-relaxed text-muted-foreground sm:text-[0.95rem]"
              >
                {paragraph}
              </p>
            ))}
          </div>
        </Reveal>
      </section>

      {/* Features */}
      {detail.features.length > 0 && (
        <section className="mt-14">
          <Reveal>
            <SectionHeading title="Key Features" icon={Sparkles} />
          </Reveal>
          <div className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {detail.features.map((feature, i) => (
              <Reveal key={feature.title} delay={i * 0.05} className="h-full">
                <Card className="h-full hover:-translate-y-1 hover:border-primary/25 hover:shadow-[var(--shadow-lift)]">
                  <CardHeader>
                    <IconTile icon={getDetailIcon(feature.icon)} size="sm" />
                    <h3 className="pt-2 text-sm font-semibold tracking-tight">
                      {feature.title}
                    </h3>
                    <p className="text-xs leading-relaxed text-muted-foreground">
                      {feature.description}
                    </p>
                  </CardHeader>
                </Card>
              </Reveal>
            ))}
          </div>
        </section>
      )}

      {/* How it works */}
      {detail.architecture.length > 0 && (
        <section className="mt-14">
          <Reveal>
            <SectionHeading title="How It Works" icon={Workflow} />
          </Reveal>
          <ol className="mt-6 space-y-4">
            {detail.architecture.map((step, i) => (
              <Reveal key={step.title} delay={i * 0.06}>
                <li className="flex items-start gap-4">
                  <span
                    aria-hidden="true"
                    className="mt-1 pt-0.5 font-mono text-sm font-semibold text-primary"
                  >
                    {String(i + 1).padStart(2, "0")}
                  </span>
                  <div className="min-w-0 pt-1">
                    <h3 className="text-sm font-semibold tracking-tight">
                      {step.title}
                    </h3>
                    <p className="mt-1 max-w-2xl text-sm leading-relaxed text-muted-foreground">
                      {step.description}
                    </p>
                  </div>
                </li>
              </Reveal>
            ))}
          </ol>
        </section>
      )}

      {/* Tech stack */}
      {detail.techStack.length > 0 && (
        <section className="mt-14">
          <Reveal>
            <SectionHeading title="Tech Stack" icon={Layers} />
          </Reveal>
          <div className="mt-6 space-y-5">
            {detail.techStack.map((group, i) => (
              <Reveal key={group.category} delay={i * 0.05}>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.16em] text-primary">
                    {group.category}
                  </p>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {group.items.map((item) => (
                      <Badge key={item} variant="secondary">
                        {item}
                      </Badge>
                    ))}
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
        </section>
      )}

      {/* Highlights */}
      {detail.highlights.length > 0 && (
        <section className="mt-14">
          <Reveal>
            <SectionHeading title="Highlights" icon={Award} />
          </Reveal>
          <ul className="mt-6 grid gap-3 sm:grid-cols-2">
            {detail.highlights.map((highlight, i) => (
              <Reveal key={highlight} delay={i * 0.05} className="h-full">
                <li className="flex h-full items-start gap-3 border border-border bg-card px-5 py-4 shadow-[var(--shadow-soft)]">
                  <Sparkles
                    className="mt-0.5 h-4 w-4 shrink-0 text-primary"
                    aria-hidden="true"
                  />
                  <span className="text-sm leading-relaxed text-foreground/85">
                    {highlight}
                  </span>
                </li>
              </Reveal>
            ))}
          </ul>
        </section>
      )}

      {/* CTA */}
      <Reveal className="mt-16">
        <div className="border-y-2 border-foreground bg-card/50 p-8 text-center sm:p-10">
          <h2 className="font-display text-xl font-semibold tracking-tight">
            Explore {project.name}
          </h2>
          <p className="mx-auto mt-2 max-w-xl text-sm text-muted-foreground">
            {project.tagline} — the full source is on GitHub.
          </p>
          <div className="mt-5 flex flex-wrap justify-center gap-2">
            <a
              href={project.repo}
              target="_blank"
              rel="noopener noreferrer"
              className={buttonVariants({ variant: "default", size: "sm" })}
            >
              <Github aria-hidden="true" />
              View source
            </a>
            {project.demo && (
              <a
                href={project.demo}
                target="_blank"
                rel="noopener noreferrer"
                className={buttonVariants({ variant: "outline", size: "sm" })}
              >
                <ExternalLink aria-hidden="true" />
                Open the live site
              </a>
            )}
            {project.dmg && (
              <a
                href={project.dmg}
                className={buttonVariants({ variant: "outline", size: "sm" })}
              >
                <Download aria-hidden="true" />
                Download DMG
              </a>
            )}
          </div>
        </div>
      </Reveal>
    </div>
  );
}
